package com.foreknow.controller;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CookieDemo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        (1) 创建一个 Cookie 对象：您可以调用带有 cookie 名称和 cookie 值的 Cookie 构造函数，cookie 名称和 cookie 值都是字符串。
            //Cookie cookie = new Cookie("name","tom123");
//        (2) 设置最大生存周期：您可以使用 setMaxAge 方法来指定 cookie 能够保持有效的时间（以秒为单位）。下面将设置一个最长有效期为 1个月 小时的 cookie。
            //cookie.setMaxAge(1*30*24*60*60);
//        (3) 发送 Cookie给客户端
            //resp.addCookie(cookie);
        //如何读取客户端的Cookie
        Cookie[] cookies = req.getCookies();
        if(cookies!=null) {
            for (Cookie c:cookies) {
                String name = c.getName();
                String value = c.getValue();
                System.out.println(name + "---" + value);
            }
        }else {
            System.out.println("no cookies......");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}
